#include "fan.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static int write_text_file(const char *path, const char *text)
{
    FILE *f = fopen(path, "w");
    if (!f) return -1;
    int ok = fputs(text, f) >= 0;
    fclose(f);
    return ok ? 0 : -1;
}

// Write 0..100 directly to sysfs PWM path (example-style)
static int fan_write_pwm_percent(int percent)
{
    const char *p = getenv("FAN_PWM_PATH");
    if (!p || !*p) p = "/sys/class/hwmon/hwmon1/pwm1";
    if (percent < 0) percent = 0; if (percent > 100) percent = 100;
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", percent);
    return write_text_file(p, buf);
}

int fan_set_on(int on)
{
    return fan_write_pwm_percent(on ? 100 : 0);
}

int fan_set_speed(int percent)
{
    if (percent <= 0) return fan_write_pwm_percent(0);
    if (percent >= 100) return fan_write_pwm_percent(100);
    return fan_write_pwm_percent(percent);
}

// Match example/fan.c behavior: >29°C => on, else off
int control_fan(float temperature)
{
    if (temperature > 29.0f) {
        int rc = fan_set_on(1);
        if (rc == 0) printf("风扇已打开\n"); else fprintf(stderr, "风扇打开失败\n");
        return rc;
    } else {
        int rc = fan_set_on(0);
        if (rc == 0) printf("风扇已关闭\n"); else fprintf(stderr, "风扇关闭失败\n");
        return rc;
    }
}

